package com.project.controller;

import com.google.code.kaptcha.Producer;
import com.project.util.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码控制器
 *
 * @author Leo高洋
 * @create 2023-03-04 14:54
 */
@RestController
public class CaptchaController {
    @Autowired
    private Producer producer;

    private final static Logger logger = LoggerFactory.getLogger(CaptchaController.class);

    @GetMapping("/captcha")
    public R captcha() throws IOException {
        String code = producer.createText();// 生成验证码
        logger.info("验证码是：" + code);

        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);

        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("base64Img", base64Img);
        resultMap.put("captcha", code);
        return R.ok(resultMap);
    }
}
